% 逻辑操作实现边缘检测
%原始图像
img=imread("img\rice.png");
figure,imshow(img),xlabel("原图");
pause;

%--------------------
%原始图像数据二值化
img=im2bw(img);
% img=imbinarize(img);
figure,imshow(img),xlabel("二值图");
% pause

%--------------------
%基于逻辑运算的边缘检测
imgSize=size(img);
row=imgSize(1,1);%行
col=imgSize(1,2);%列
%[row,col]=size(img);

%--------------------
%第一步：左移
imgLeftA=img;
figure,subplot(4,4,1),imshow(imgLeftA),xlabel("(a1)原图"),ylabel("向左");
imgLeftB=imgLeftA;
imgLeftB(:,1)=[];
imgLeftB=[imgLeftB ones(row,1)];%左移
subplot(4,4,2),imshow(imgLeftB),xlabel("(b1)左移");
imgLeftC=imgLeftA|imgLeftB;%或运算
subplot(4,4,3),imshow(imgLeftC),xlabel("(c1):a1 or b1");
imgLeftD=xor(imgLeftA,imgLeftC);%异或运算
subplot(4,4,4),imshow(imgLeftD),xlabel("(d1):a1 xor c1");

%--------------------
%第二步：右移
imgRightA=img;
subplot(5,4,5),imshow(imgRightA),xlabel("(a2)原图"),ylabel("向右");
imgRightB=imgRightA;
imgRightB(:,col)=[];
imgRightB=[ones(row,1) imgRightB];
imgRightC=imgRightA|imgRightB;
imgRightD=xor(imgRightA,imgRightC);
subplot(4,4,6),imshow(imgRightB),xlabel("(b2)右移");
subplot(4,4,7),imshow(imgRightC),xlabel("(c2):a2 or b2");
subplot(4,4,8),imshow(imgRightD),xlabel("(d2):a2 xor c2");

%--------------------
%第三步：上移
imgUpA=img;
subplot(5,4,9),imshow(imgUpA),xlabel("(a3)原图"),ylabel("向上");
imgUpB=imgUpA;
imgUpB(1,:)=[];
imgUpB=[imgUpB;ones(1,col)];
imgUpC=imgUpA|imgUpB;
imgUpD=xor(imgUpA,imgUpC);
subplot(4,4,10),imshow(imgUpB),xlabel("(b3)上移");
subplot(4,4,11),imshow(imgUpC),xlabel("(c3):a3 or b3");
subplot(4,4,12),imshow(imgUpD),xlabel("(d3):a3 xor c3");

%--------------------
%第四步：下移
imgDownA=img;
subplot(5,4,13),imshow(imgDownA),xlabel("(a4)原图"),ylabel("向下");
imgDownB=imgDownA;
imgDownB(row,:)=[];
imgDownB=[ones(1,col);imgDownB];
imgDownC=imgDownA|imgDownB;
imgDownD=xor(imgDownA,imgDownC);
subplot(4,4,14),imshow(imgDownB),xlabel("(b4)下移");
subplot(4,4,15),imshow(imgDownC),xlabel("(c4):a4 or b4");
subplot(4,4,16),imshow(imgDownD),xlabel("(d4):a4 xor c4");
%--------------------
%第五步：结果或
pause;
figure,imshow(imgLeftD|imgRightD|imgUpD|imgDownD),xlabel("结果或图");